package com.ks.pc.controller.asyn;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;

import com.alibaba.fastjson.JSONObject;
import com.ks.dto.BrandDto;
import com.ks.dto.ClassifyDto;
import com.ks.dto.ImgDto;
import com.ks.dto.Product2Dto;
import com.ks.dto.ResultDto;
import com.ks.pc.service.CommonService;
import com.ks.utils.Identities;

/**
 * 
 * @author jxzhang on 2017年3月15日
 * @Verdion 1.0 版本
 */
@Controller
@RequestMapping(value = "/common")
public class CommonControllerAsyn {

	@Autowired
	private CommonService commonService;

	// /**
	// * 检查session是否过期
	// */
	// public void checkSessionTimeout() {
	// HttpSession session = request.getSession();
	// boolean activate = (boolean) session.getAttribute("activate");
	// System.out.println("=================" + activate);
	// sysController.login();
	// }

	/**
	 * 上传图片
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value = "/uploadify", method = RequestMethod.POST)
	public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Map<String, Object> map = new HashMap<String, Object>();
		request.setCharacterEncoding("utf-8");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();
		String realPath = servletContext.getRealPath("/");
		// String realPath = request.getContextPath() +"/";
		String path = realPath + "upload" + System.getProperty("file.separator") + "image";
		String serverPath = "upload" + System.getProperty("file.separator") + "image";
		System.out.println(path);

		factory.setRepository(new File(path));
		factory.setSizeThreshold(1024 * 1024);
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			// 可以上传多个文件
			@SuppressWarnings("unchecked")
			List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
			for (FileItem item : list) {
				if (!item.isFormField()) {
					String name = item.getName();
					String fileSuffix = name.substring(name.lastIndexOf(".") + 1, name.length());
					String oldName = name.replaceAll("." + fileSuffix, "");
					String fileName = Long.toString(System.currentTimeMillis());
					String newName = fileName + "." + fileSuffix;
					File file = new File(path, newName);
					FileOutputStream fileOutputStream = new FileOutputStream(file);
					OutputStream out = fileOutputStream;
					InputStream in = item.getInputStream();
					int length = 0;
					byte[] buf = new byte[1024];
					while ((length = in.read(buf)) != -1) {
						out.write(buf, 0, length);
					}
					ImgDto dto = new ImgDto();
					this.getParams(list, request);
					String type = (String) request.getAttribute("type");
					if (null == type) {
						in.close();
						out.close();
						return;
					}
					serverPath += System.getProperty("file.separator") + newName;
					dto.setType(Integer.parseInt(type));
					dto.setImgPaths(serverPath);
					String imgId = Long.toString(Identities.unionRandomLong());
					dto.setId(imgId);
					commonService.insertImgDto(dto);
					in.close();
					out.close();
					/** 将上传处理后的数据返回 **/
					map.put("id", imgId);
					map.put("fileName", newName);
					map.put("fileSuffix", fileSuffix);
					map.put("oldName", oldName);
					map.put("filePath", serverPath);
					break;
				}
			}
		} catch (Exception e) {
			System.out.println("出错了：" + e.getMessage());
		}
		response.setContentType("text/xml; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		PrintWriter out = response.getWriter();
		JSONObject jsonObject = new JSONObject();
		String msg = jsonObject.toJSONString(map);
		out.print(msg);
		out.close();
	}

	private void getParams(List<FileItem> list, HttpServletRequest request) throws UnsupportedEncodingException {
		if (null == list) {
			return;
		}
		for (FileItem item : list) {
			if (item.isFormField()) {
				String name = item.getFieldName();
				String value = item.getString("gbk");
				request.setAttribute(name, value);
			}
		}
	}

	/**
	 * 获得所有类
	 * 
	 * @return ResultDto<List<ClassifyDto>>
	 */
	@ResponseBody
	@RequestMapping(value = "/queryClassifyAll", method = RequestMethod.POST)
	public ResultDto<List<ClassifyDto>> queryClassifyAll() {
		ResultDto<List<ClassifyDto>> result = new ResultDto<List<ClassifyDto>>();
		List<ClassifyDto> list = commonService.queryClassifyAll();
		boolean isSuccess = false;
		if (null != list) {
			result.setBody(list);
			result.setStatus(200);
			isSuccess = true;
		}
		result.setType(isSuccess);
		return result;
	}

	/**
	 * 通过分类Id获取所有品牌
	 * 
	 * @param classifyId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryBrandAllByClassifyId", method = RequestMethod.POST)
	public ResultDto<List<BrandDto>> queryBrandAllByClassifyId(Integer classifyId) {
		ResultDto<List<BrandDto>> result = new ResultDto<List<BrandDto>>();
		
		List<BrandDto> list = commonService.queryBrandAllByClassifyId(classifyId);
		boolean isSuccess = false;
		if (null != list) {
			result.setBody(list);
			result.setStatus(200);
			isSuccess = true;
		}
		result.setType(isSuccess);
		return result;
	}

	/**
	 * 通过品牌Id获取所有产品
	 * 
	 * @param brandId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryProductAllByBrandId", method = RequestMethod.POST)
	public ResultDto<List<Product2Dto>> queryProductAllByBrandId(Integer brandId) {
		ResultDto<List<Product2Dto>> result = new ResultDto<List<Product2Dto>>();
		List<Product2Dto> list = commonService.queryProductAllByBrandId(brandId);
		boolean isSuccess = false;
		if (null != list) {
			result.setBody(list);
			result.setStatus(200);
			isSuccess = true;
		}
		result.setType(isSuccess);
		return result;
	}

	/**
	 * 通过品牌Id获取所有产品
	 * 
	 * @param brandId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryProductAllByClassifyId", method = RequestMethod.POST)
	public ResultDto<List<Product2Dto>> queryProductAllByClassifyId(Integer classifyId) {
		ResultDto<List<Product2Dto>> result = new ResultDto<List<Product2Dto>>();

		List<Product2Dto> rs = commonService.queryProductAllByClassifyId(classifyId);
		boolean isSuccess = false;
		if (null != rs) {
			result.setBody(rs);
			result.setStatus(200);
			isSuccess = true;
		}
		result.setType(isSuccess);
		return result;
	}
}
